<?php

class BookController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
// 				'ajaxOnly + GetFcode',
			'accessControl', // perform access control for CRUD operations
			
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','copy','getFcode'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Book;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Book']))
		{
			$model->attributes=$_POST['Book'];
			if($model->save())
			{
				//先记录操作
				$this->LogRecord($model->bookID, Logs::BOOK_CREATE, '');
				$this->redirect(array('view','id'=>$model->bookID));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Book']))
		{
			$model->attributes=$_POST['Book'];
			if($model->save())
			{
				//先记录操作
				$this->LogRecord($model->bookID, Logs::BOOK_UPDATE, '');
				$this->redirect(array('view','id'=>$model->bookID));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model=$this->loadModel($id);
			$descript = '图书编号：'.$model->bookID. '  书名：'.$model->bookName. '；作者：'. $model->author . '；ISBN：' . $model->ISBN;
						
			
			
			
	
	
			if($model->delete())
				$this->LogRecord($model->bookID, Logs::BOOK_DEL, $descript);
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Book');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Book('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Book']))
			$model->attributes=$_GET['Book'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Book::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='book-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * 套录指定ID的图书。
	 * 创建成功后，将重定向到“显示”页面，浏览存入的书目信息。
	 * @param 整数 $id 是套录图书的ID。
	 */
	public function actionCopy($id)
	{
		$model=$this->loadModel($id);
		$model->isNewRecord = true;
		$model->bookID=null;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
	
		if(isset($_POST['Book']))
		{
			$model->attributes=$_POST['Book'];
			if($model->save())
			{
				$this->LogRecord($model->bookID, Logs::BOOK_CREATE, '');
				$this->redirect(array('view','id'=>$model->bookID));
			}
	
		}
	
	
		$this->render('create',array(
				'model'=>$model,
		));
	}
	
	/**
	 * 记录对书目信息的新建、更新、删除操作和事件。
	 * @param 整数 $id 是图书的ID
	 * @param 字符串 $action 是对书目的操作类型表述
	 * @param 字符串 $descipt 是对操作的补充描述
	 */
	protected function LogRecord($id,$action,$descipt){
		$rec = new Logs();
		$rec->bookID = $id;
		$rec->name = Yii::app()->user->name;
		$rec->operate = $action;
		$rec->date = date("Y-m-d H:i:s");
		$rec->descript = $descipt;
		$rec->optTable = Logs::OPT_TAB_BOOK;
	
		$rec->save();
	
	}
	
	/**
	 * 根据图书馆对图书四角编码的规范，给指定的字符串进行四角编码查询。
	 * 如果字库中不存在该汉字，不知如何进行错误信息传递及处理。
	 * @param string $letter	要进行四角编码的字符串。
	 */
	public function actionGetFcode($letter){
		// 		echo '测试用字：'.$letter ."<br/>";
		// $_letter0 = trim($letter,' ');
		// echo 'trimed：'.$_letter0 ."<br/>";
		$_result= null;
	
		if($letter == null)
		{
			$_result ='未正确传入字符！';
			echo CJSON::encode($_result);
			return;
		}
	
		//去除空格，并截取前3个汉字（如果存在的话）；
		$_letter0= str_replace(' ', '',$letter);
		$_letter1= substr($_letter0, 0,3);
		$_letter2= substr($_letter0, 3,3);
		$_letter3= substr($_letter0, 6,3);
	
		// 		echo 'str_replace：'.$_letter0 ."<br/>";
		// 		echo 'strlen:'. strlen($_letter0) ."<br/>";
		// 		echo 'substred1：'.$_letter1 ."<br/>";
		// 		echo 'substred2：'.$_letter2 ."<br/>";
		// 		echo 'substred3：'.$_letter3 ."<br/>";
	
	
		$_result= null;
		$_strlen= strlen($_letter0);
		if($_strlen == 3)//1个汉字
		{
			$model1 =  Fcode::model()->findByPk($_letter1);
			if($model1== null ) {
				$_result ='未传入正确字符:'.$_letter1;
				echo CJSON::encode($_result);
				return;
			}
	
			//	echo '分别：'.$_letter1 . $model1->fcode;
				
			$_result = $model1->fcode;
		}
		else if($_strlen == 6)//2个汉字
		{
			$model1 =  Fcode::model()->findByPk($_letter1);
			$model2 =  Fcode::model()->findByPk($_letter2);
			if($model1 ==null)
			{
				$_result ='找不到汉字[' .$_letter1 .']的四角编码，请联系管理员进行维护！';
				echo CJSON::encode($_result);
				return;
			}
			if($model2== null)
			{
				$_result ='找不到汉字[' .$_letter2.']的四角编码，请联系管理员进行维护！';
				echo CJSON::encode($_result);
				return;
			}
				
			// 			echo '分别：'.$_letter1 . $model1->fcode .$_letter2 . $model2->fcode;
				
			$_result =substr( $model1->fcode, 0,2) . substr( $model2->fcode, 0,2);
		}
		else{
			//3个以上
			$model1 =  Fcode::model()->findByPk($_letter1);
			$model2 =  Fcode::model()->findByPk($_letter2);
			$model3 =  Fcode::model()->findByPk($_letter3);
	
	
			if($model1 ==null)
			{
				$_result ='找不到汉字[' .$_letter1 .']的四角编码，请联系管理员进行维护！';
				echo CJSON::encode($_result);
				return;
			}
			if($model2== null)
			{
				$_result ='找不到汉字[' .$_letter2.']的四角编码，请联系管理员进行维护！';
				echo CJSON::encode($_result);
				return;
			}
			if($model3 ==null)
			{
				$_result ='找不到汉字[' .$_letter3.']的四角编码，请联系管理员进行维护！';
				echo CJSON::encode($_result);
				return;
			}
	
			// 			echo '分别：'.$_letter1 . $model1->fcode .$_letter2 . $model2->fcode .$_letter3 . $model3->fcode .'<br/>';
	
			$_result =substr( $model1->fcode, 0,2) . substr( $model2->fcode, 0,1). substr( $model3->fcode, 0,1);
		}
	
		echo CJSON::encode($_result);
		// 		if($model1 != null)
			// 			echo '四角编码：'.$_result ;
	}
	
}
